import api from '../../utils/api.js';
import Cache from '../../utils/cache.js';

Page({
  data: {
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1,
    today: new Date().getDate(),
    selectedDate: new Date().getDate(),
    days: [],
    signedDays: [], // 已签到的日期
    signCount: 0, // 连续签到天数
    loading: true,
    showSignSuccess: false, // 控制签到成功弹窗显示
    userId: '', // 用户ID
    rewardPoints: 5 // 签到奖励积分
  },

  onLoad: function (options) {
    // 获取缓存中的用户ID
    const userId = wx.getStorageSync('userId'); // 修改这里
    if (userId) {
      this.setData({ userId });
      console.log('签到页面获取到用户ID:', userId);
    } else {
      console.error('未找到用户ID，请先登录');
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 2000
      });
      // 延迟返回
      setTimeout(() => {
        wx.navigateBack();
      }, 2000);
      return;
    }
    
    this.initCalendar();
    this.getSignCount();
  },

  onShow: function () {
    // 每次显示页面时重新获取用户ID
    const userId = wx.getStorageSync('userId'); // 修改这里
    if (userId) {
      this.setData({ userId });
      this.getSignCount();
    }
  },

  // 初始化日历
  initCalendar: function () {
    const days = this.calculateDays(this.data.year, this.data.month);
    this.setData({
      days: days
    });
  },

  // 计算当前月的天数和每天对应的星期
  calculateDays: function (year, month) {
    const days = [];
    // 获取当月的天数
    const daysInMonth = new Date(year, month, 0).getDate();
    
    // 获取当月第一天是星期几 (0-6, 0是星期日)
    const firstDayOfMonth = new Date(year, month - 1, 1).getDay();
    
    // 添加上个月的占位天数
    for (let i = 0; i < firstDayOfMonth; i++) {
      days.push({
        day: null,
        isToday: false,
        isSelected: false,
        isSigned: false
      });
    }
    
    // 添加当月的天数
    for (let i = 1; i <= daysInMonth; i++) {
      days.push({
        day: i,
        isToday: i === this.data.today,
        isSelected: i === this.data.selectedDate,
        isSigned: false // 默认未签到，后续会更新
      });
    }
    
    return days;
  },

  // 获取签到统计和已签到日期
  getSignCount: function () {
    if (!this.data.userId) {
      console.error('未找到用户ID，无法获取签到统计');
      return;
    }
    
    this.setData({ loading: true });
    
    api.getUserSignCount(this.data.userId).then(res => {
      console.log('获取签到统计成功:', res);
      
      if (res.data && res.data.code === 200) {
        // 确保获取到的是数字类型
        let signCount = 0;
        if (typeof res.data.data === 'number') {
          signCount = res.data.data;
        } else if (res.data.data && typeof res.data.data === 'object') {
          // 如果返回的是对象，尝试获取count属性
          signCount = res.data.data.count || 0;
        } else {
          console.warn('签到数据格式异常:', res.data.data);
        }
        
        console.log('解析后的签到天数:', signCount);
        
        // 更新签到天数
        this.setData({
          signCount: signCount,
          loading: false
        });
        
        // 更新日历中已签到的日期
        this.updateSignedDays(this.getSignedDaysFromCount(signCount));
      } else {
        console.error('获取签到统计失败:', res);
        this.setData({ loading: false });
        wx.showToast({
          title: '获取签到记录失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      console.error('获取签到统计异常:', err);
      this.setData({ loading: false });
      wx.showToast({
        title: '获取签到记录失败',
        icon: 'none'
      });
    });
  },
  
  // 根据连续签到天数计算已签到日期
  getSignedDaysFromCount: function(count) {
    const signedDays = [];
    const today = this.data.today;
    
    // 从今天开始往前推count天
    for (let i = 0; i < count; i++) {
      const day = today - i;
      if (day > 0) { // 确保日期在当月内
        signedDays.push(day);
      }
    }
    
    return signedDays;
  },

  // 更新日历中已签到的日期
  updateSignedDays: function (signedDays) {
    const days = this.data.days;
    
    // 将已签到的日期标记为已签到
    signedDays.forEach(day => {
      const dayIndex = days.findIndex(d => d.day === day);
      if (dayIndex !== -1) {
        days[dayIndex].isSigned = true;
      }
    });
    
    this.setData({
      days: days,
      signedDays: signedDays
    });
  },

  // 选择日期
  selectDate: function (e) {
    const { day } = e.currentTarget.dataset;
    if (!day) return; // 忽略空白日期
    
    const days = this.data.days.map(d => {
      if (d.day === day) {
        return { ...d, isSelected: true };
      } else {
        return { ...d, isSelected: false };
      }
    });
    
    this.setData({
      selectedDate: day,
      days: days
    });
    
    // 如果选中的是今天，并且今天还未签到，提示用户签到
    if (day === this.data.today && !this.data.signedDays.includes(day)) {
      wx.showToast({
        title: '点击下方按钮签到',
        icon: 'none',
        duration: 1500
      });
    }
  },

  // 切换月份
  changeMonth: function(e) {
    const { type } = e.currentTarget.dataset;
    let { year, month } = this.data;
    
    if (type === 'prev') {
      if (month === 1) {
        year--;
        month = 12;
      } else {
        month--;
      }
    } else {
      if (month === 12) {
        year++;
        month = 1;
      } else {
        month++;
      }
    }
    
    this.setData({
      year,
      month
    });
    
    this.initCalendar();
    this.getSignCount();
  },

  // 签到
  signIn: function () {
    if (!this.data.userId) {
      console.error('未找到用户ID，无法签到');
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    
    if (this.data.signedDays.includes(this.data.today)) {
      wx.showToast({
        title: '今日已签到',
        icon: 'none'
      });
      return;
    }
    
    wx.showLoading({
      title: '签到中...',
    });
    
    // 打印签到请求参数
    console.log('发起签到请求，用户ID:', this.data.userId);
    
    api.userSignIn(this.data.userId).then(res => {
      wx.hideLoading();
      console.log('签到结果:', res);
      
      // 无论后端返回什么，都尝试解析
      if (res.data) {
        const isSuccess = res.data.code === 200 || res.data.code === 0;
        
        if (isSuccess) {
          // 签到成功，播放成功动画
          try {
            wx.vibrateShort({
              type: 'medium'
            });
          } catch (e) {
            console.warn('振动API调用失败:', e);
          }
          
          // 更新签到天数和状态
          const newSignCount = this.data.signCount + 1;
          this.setData({
            showSignSuccess: true,
            signCount: newSignCount,
            rewardPoints: this.calculateRewardPoints(newSignCount)
          });
          
          // 手动更新今天的签到状态
          const days = [...this.data.days];
          const todayIndex = days.findIndex(d => d.day === this.data.today);
          if (todayIndex !== -1) {
            days[todayIndex].isSigned = true;
            this.setData({
              days,
              signedDays: [...this.data.signedDays, this.data.today]
            });
          }
          
          // 3秒后自动关闭成功提示
          setTimeout(() => {
            this.setData({
              showSignSuccess: false
            });
          }, 3000);
        } else {
          const errorMsg = res.data.msg || '签到失败，请稍后再试';
          console.error('签到失败:', errorMsg);
          wx.showToast({
            title: errorMsg,
            icon: 'none'
          });
        }
      } else {
        wx.showToast({
          title: '签到失败，服务器响应异常',
          icon: 'none'
        });
      }
    }).catch(err => {
      wx.hideLoading();
      console.error('签到异常:', err);
      wx.showToast({
        title: '签到失败，请检查网络连接',
        icon: 'none'
      });
    });
  },
  
  // 计算奖励积分 (连续签到天数越多，奖励越多)
  calculateRewardPoints: function(signCount) {
    if (signCount <= 5) {
      return 5; // 基础积分
    } else if (signCount <= 15) {
      return 10; // 进阶积分
    } else if (signCount <= 30) {
      return 15; // 高级积分
    } else {
      return 20; // 超级积分
    }
  },

  // 关闭签到成功弹窗
  closeSuccessPopup: function () {
    this.setData({
      showSignSuccess: false
    });
  },

  // 返回上一页
  goBack: function () {
    wx.navigateBack();
  }
});